from flask import Blueprint, render_template, jsonify, request
from flask_login import login_required, current_user
from applications.common.utils.rights import authorize
from applications.models import Category
from applications.schemas import CategorySchema
from sqlalchemy import desc
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.curd import get_one_by_id
from applications.common.utils.validate import str_escape
from applications.extensions import db
import datetime

bp = Blueprint('category', __name__, url_prefix='/category')


# 首页
@bp.get('/')
def index():
    user = current_user
    return render_template('blog/category/main.html', user=user)

# 资源数据
@bp.get('/data')
# @authorize("blog:category:main")
def data():
    limit = str_escape(request.args.get('limit', type=int))
    type = str_escape(request.args.get('type', type=str)) or ""
    if int(limit) > 1000 or int(limit) < 0:
        limit = 100
    category_name = str_escape(request.args.get('categoryName', type=str))
    # filters = [Category.is_del==0]
    filters = []
    if category_name:
        filters.append(Category.name.contains(category_name))
    categorys = Category.query.filter(*filters).order_by(desc(Category.id)).layui_paginate()
    return table_api(data=CategorySchema(many=True).dump(categorys), count=categorys.total,limit=limit)


# 资源删除
@bp.delete('/remove/<int:id>')
@authorize("blog:category:remove", log=True)
def remove(id):
    r = Category.query.filter_by(id=id).update({"is_del": 1})
    db.session.commit()
    if not r:
        return fail_api(msg="资源删除失败")
    return success_api(msg="资源删除成功")


#资源增加
@bp.get('/add')
@authorize("blog:category:add", log=True)
def add():
    return render_template('blog/category/add.html')


# 角色增加
@bp.post('/save')
@authorize("blog:category:add", log=True)
def save():
    req = request.get_json(force=True)
    name = str_escape(req.get("name"))
    category = Category(
        name=name,
        is_del=0
    )
    db.session.add(category)
    db.session.commit()
    return success_api(msg="成功")


# 资源编辑
@bp.get('/edit/<int:id>')
@authorize("blog:category:edit", log=True)
def edit(id):
    r = get_one_by_id(model=Category, id=id)
    return render_template('blog/category/edit.html', category=r)


# 更新资源
@bp.put('/update')
@authorize("blog:category:edit", log=True)
def update():
    req_json = request.get_json(force=True)
    id = req_json.get("categoryId")
    data = {
        "name": str_escape(req_json.get("categoryName")),
        "is_del": str_escape(req_json.get("isDel"))
    }
    category = Category.query.filter_by(id=id).update(data)
    db.session.commit()
    if not category:
        return fail_api(msg="更新资源失败")
    return success_api(msg="更新资源成功")
